<template>
  <div>
    <!-- 显示当前评论的cell -->
    <van-cell>
      <div class="cmt-box">
        <van-image fit="cover" round :src="currentItem.aut_photo"></van-image>
        <!-- 中间核心区域 -->
        <div class="center-box">
          <div class="name">{{ currentItem.aut_name }}</div>
          <div class="content">{{ currentItem.content }}</div>
          <div class="time">
            <span>{{ $relvTime(currentItem.pubdate) }}</span>
          </div>
        </div>
      </div>
    </van-cell>
    <!-- 分割线 -->
    <van-divider>回复列表</van-divider>
    <!-- list -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.com_id">
        <div class="cmt-box">
          <van-image fit="cover" round :src="item.aut_photo"></van-image>
          <!-- 中间核心区域 -->
          <div class="center-box">
            <div class="name">{{ item.aut_name }}</div>
            <div class="content">{{ item.content }}</div>
            <div class="time">
              <span>{{ $relvTime(item.pubdate) }}</span>
            </div>
          </div>
        </div>
      </van-cell>
    </van-list>
    <!-- 放固定定位的div，里面放输入框和按钮 -->
    <div class="send-box">
      <van-field
        v-model="cmt"
        center
        clearable
        placeholder="请输入评论内容"
        @keyup.enter="send"
      >
        <template #button>
          <van-button @click="send" size="small" type="info">发布</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
// 导入接口
import { cmtListAPI, sendCmtAPI } from '@/api/comment'
export default {
  props: {
    currentItem: {
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      cmt: '',
      offset: null
    }
  },
  methods: {
    // 发表回复
    async send () {
      if (this.cmt === '') {
        return this.$toast('请输入评论内容')
      }
      // 能来到这肯定不为空
      const res = await sendCmtAPI({
        // 如果是回复，传评论id
        target: this.currentItem.com_id,
        // 评论的内容
        content: this.cmt,
        art_id: this.$route.params.id
      })

      // 清空输入内容
      this.cmt = ''
      // 把服务器返回的最新的这条评论直接加到数组里
      this.list.unshift(res.data.new_obj)
      // 把当前评论的回复数量+1
      this.$emit('add')
    },
    async onLoad () {
      const res = await cmtListAPI({
        type: 'c',
        source: this.currentItem.com_id,
        offset: this.offset,
        limit: 5
      })

      this.list.push(...res.data.results)
      // 把本次的最后一个id存起来
      this.offset = res.data.last_id
      // 加载本次加载状态
      this.loading = false
      // 判断数组的长度大于或等于服务器告诉的总数量就代表加载完了
      if (this.list.length >= res.data.total_count) {
        this.finished = true
      }
    }
  }
}
</script>

<style></style>
